import cv2
import numpy as np

import matplotlib
matplotlib.use('TkAgg')
import matplotlib.pyplot as plt

# https://blog.csdn.net/u010128736/article/details/52801310

def calcAndDrawHist(img):
    hist = cv2.calcHist([img],
                        [0],  # 使用的通道
                        None,  # 没有使用mask
                        [256],  # HistSize
                        [0.0, 255.0])  # 直方图柱的范围

    plt.plot(hist)

    plt.show()


def Otsu(image):
    gray = image #cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

    plt.subplot(131), plt.imshow(image, "gray")
    plt.title("source image"), plt.xticks([]), plt.yticks([])
    plt.subplot(132), plt.hist(image.ravel(), 256)
    plt.title("Histogram"), plt.xticks([]), plt.yticks([])
    ret1, th1 = cv2.threshold(gray, 0, 255, cv2.THRESH_OTSU)  # 方法选择为THRESH_OTSU
    plt.subplot(133), plt.imshow(th1, "gray")
    plt.title("OTSU,threshold is " + str(ret1)), plt.xticks([]), plt.yticks([])
    plt.show()



if __name__ == '__main__':
    mi = cv2.imread('imgs/mi.png', 0)  # 直接读为灰度图像
    pic2 = cv2.imread('imgs/pic2.png', 0)
    pic6 = cv2.imread('imgs/pic6.png', 0)
    # cv2.imshow('img', mi)

    # 绘制直方图
    # calcAndDrawHist(mi)

    # Otsu(mi)
    # Otsu(pic2) # otsu处理有噪点的不行噪点
    Otsu(pic6)  # otsu处理渐变的也不行

    cv2.waitKey(0)
    cv2.destroyAllWindows()
